<?php
/**
 *+------------------
 * Lflow
 *+------------------
 * Copyright (c) 2023~2030 gitee.com/liu_guan_qing All rights reserved.本版权不可删除，侵权必究
 *+------------------
 * Author: Mr.April(405784684@qq.com)
 *+------------------
 */
declare (strict_types=1);

namespace lflow\handlers\impl;

use lflow\model\ForkModel;
use lflow\model\JoinModel;
use lflow\model\NodeModel;
use lflow\model\WorkModel;
use lflow\handlers\impl\StringBuilder;

/**
 * 合并分支操作处理器
 *
 * @author Mr.April
 * @since  1.0
 */
class MergeBranchHandler extends AbstractMergeHandler
{

    private JoinModel $model;

    /**
     * @param \lflow\model\JoinModel $model
     */
    public function __construct(JoinModel $model)
    {
        $this->model = $model;
    }

    /**
     * 对join节点的所有输入变迁进行递归，查找join至fork节点的所有中间task元素
     *
     * @param \lflow\model\NodeModel             $node
     * @param \lflow\handlers\impl\StringBuilder $buffer
     */
    private function findForkTaskNames(NodeModel $node, StringBuilder $buffer): void
    {
        //循环到分支停止
        if ($node instanceof ForkModel) {
            return;
        }
        $inputs = $node->getInputs();
        foreach ($inputs as $tm) {
            if ($tm->getSource() instanceof WorkModel) {
                $buffer->append($tm->getSource()->getName());
            }
            $this->findForkTaskNames($tm->getSource(), $buffer);
        }
    }

    /**
     * 对join节点的所有输入变迁进行递归，查找join至fork节点的所有中间task元素
     *
     * @return string
     */
    protected function findActiveNodes(): string
    {
        $buffer = new StringBuilder();
        $this->findForkTaskNames($this->model, $buffer);
        return $buffer->toString();
    }
}
